import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state={
  //获取当前是否是授权状态
  isAuthenticated:false,
  //存储用户信息
  user:{},
  // 商品信息
  cartGoods:[]
}
// 用于对Store的数据进行加工形成新的数据
const getters = {
  isAuthenticated:state=>state.isAuthenticated,
  user:state=>state.user,
  cartGoods:state=>state.cartGoods
}
// 变更Store的数据
const mutations = {
  // 更改状态信息
  // 该方法接收两个参数
  setAuthenticated(state,isAuthenticated){
    if(isAuthenticated) state.isAuthenticated = isAuthenticated
    else state.isAuthenticated = false
  },
  setUser(state,user){
    if(user) state.user = user
    else state.user = {}
  },
  setCartGoods(state,goods){
    let flag = true
    if(goods) {
      // 一开始加
      if(state.cartGoods.length>0){
        for(let i=0;i<state.cartGoods.length;i++){
          // 同一个
          if(state.cartGoods[i]._id === goods._id){
            state.cartGoods[i].num += goods.num
            flag = false
            break
          }
        }
        // 不是同一个
        if(flag){
          state.cartGoods.push(goods)
        }
      }else{
        state.cartGoods.push(goods)
      }
    }
  },
  clearCart(state, goods) {
    if(goods) {
      state.cartGoods.forEach((item,index) => {
        if(item._id === goods._id){
          state.cartGoods.splice(index,1)
        }
      });
    }else{
      state.cartGoods = []
    }
  }
}
const actions = {
  // 异步操作（用来调用mutation）
  setAuthenticated:({commit},isAuthenticated)=>{
    commit("setAuthenticated",isAuthenticated)
  },
  setUser:({commit},user)=>{
    commit("setUser",user)
  },
  setCartGoods:({commit},goods)=>{
    commit("setCartGoods",goods)
  },
  // 统一清空user和isAuthenticated
  clearCurrentState:({commit})=>{
    commit("setAuthenticated",false)
    commit("setUser",null)
  },
  // 清空购物车或者删除商品
  clearCart:({commit},goods)=>{
    commit("clearCart",goods)
  },
}

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters,
})
